package com.itheima.health.interceptor;

import com.itheima.health.common.SessionConst;
import com.itheima.health.exception.BusinessRuntimeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 登录拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取session 如果不存在则表明未登录，拒绝请求
        HttpSession session = request.getSession();
        if (null==session || StringUtils.isEmpty(session.getAttribute(SessionConst.SESSION_USERNAME))){
            log.info("用户未登录，拦截请求--{},请求方式--{}",request.getPathInfo(),request.getMethod());
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            throw new BusinessRuntimeException("用户未登录");
        }
        //登录成功，放行
        return true;
    }
}
